package CGW.controller;

import CGW.bean.User;
import CGW.dao.UserDao;
import CGW.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class UserLoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("login.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        String pwd = req.getParameter("pwd");
        UserService service = new UserService(new UserDao());
        User user = service.login(name,pwd);
        if (user == null){
            req.setAttribute("error", "口令错误或者口令错误");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }else {
            req.getSession().setAttribute("login_user", user);
            if(user.getIs_admin()==1){
                resp.sendRedirect("admin.jsp");
            }else{
                resp.sendRedirect("/userlook1");
            }
        }
    }
}
